package com.huangpuweb.api.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class HttpRequestUtils {

    private transient static Logger log = LoggerFactory.getLogger(HttpRequestUtils.class);

 
    public static String doGet(String url) throws Exception {
        org.apache.http.client.HttpClient httpClient = new DefaultHttpClient();
        HttpGet get = new HttpGet(url);
        String content = null;
        HttpResponse response = httpClient.execute(get);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            //判断gzip,解压缩
            if (!Utils.isObjectEmpty(response.getLastHeader("Content-Encoding")) && (response.getLastHeader("Content-Encoding").toString()).indexOf("gzip") >= 0) {
                response.setEntity(new GzipDecompressingEntity(response.getEntity()));
            }
            HttpEntity httpEntity = response.getEntity();
            content = EntityUtils.toString(httpEntity);
        }
        log.info(content);
        return content;
    }

    public static String doPost(String url, Map<String, String> param) throws Exception {
        //创建HttpClient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse httpResponse = null;
        try {
            // 创建HttpPost对象
            HttpPost httpPost = new HttpPost(url);

            if (param != null && !param.isEmpty()) {
                List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
                for (String key : param.keySet()) {
                    params.add(new BasicNameValuePair(key, param.get(key) == null ? "" : param.get(key).toString()));
                }
                httpPost.setEntity(new UrlEncodedFormEntity(params, Charset.forName("UTF-8")));
            }

            //设置请求和传输超时时间
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();
            httpPost.setConfig(requestConfig);

            // 开始执行http请求
            long startTime = System.currentTimeMillis();
            httpResponse = httpclient.execute(httpPost);
            long endTime = System.currentTimeMillis();

            // 获得响应状态码
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            log.info("调用API花费时间(单位：毫秒)：" + (endTime - startTime));

            // 取出应答字符串
            HttpEntity httpEntity = httpResponse.getEntity();
            resultString = EntityUtils.toString(httpEntity, Charset.forName("UTF-8"));
            // 判断返回状态是否为200
            if (statusCode != HttpStatus.SC_OK) {
                log.error("请求接口" + url + "返回错误:" + String.format("\tStatus:%s\tError Message:%s", statusCode, resultString));
                throw new Exception(String.format("\n\tStatus:%s\n\tError Message:%s", statusCode, resultString));
            }

        } catch (ClientProtocolException e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (httpResponse != null) {
                    httpResponse.close();
                }
                httpclient.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
        return resultString;
    }

    public static String httpPostWithJSON(String url, JSONObject jsonParam) throws IOException {
    	
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();
        String respContent = null;
        StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");//解决中文乱码问题
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        HttpResponse resp = client.execute(httpPost);
        if (resp.getStatusLine().getStatusCode() == 200) {
            HttpEntity he = resp.getEntity();
            respContent = EntityUtils.toString(he, "UTF-8");
        }
        return respContent;
    }

    public static String httpPostWithString(String url, String jsonParam) throws IOException {

        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();
        String respContent = null;
        StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");//解决中文乱码问题
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        HttpResponse resp = client.execute(httpPost);
        System.out.println("resp.getStatusLine().getStatusCode() -----"+resp.getStatusLine().getStatusCode() );
        if (resp.getStatusLine().getStatusCode() == 200) {
            HttpEntity he = resp.getEntity();
            respContent = EntityUtils.toString(he, "UTF-8");
        }
        return respContent;
    }
    
    
    
    public static void main(String[] args) throws Exception {


        String url = "http://172.82.16.1/city_center/city/overview";
        JSONObject param = new JSONObject();

        param.put("app_key","bda5d74d824d46f48471a3e9f24ed299");
        param.put("format", "json");
        param.put("sign", "F697C5F6FD3D01633D607603ED8D54EB");
        param.put("sign_method","md5");
        param.put("timestamp", (long)1595815810);
        param.put("v", "1.0");
        try {
            String str = HttpRequestUtils.httpPostWithJSON(url, param);
            System.out.println("str------"+str);
        }catch(Exception e){
            e.printStackTrace();
        }

        
    }


}
